package com.example.demo.controller;

import com.example.demo.pojo.Result;
import com.example.demo.pojo.User;
import com.example.demo.pojo.UserDTO;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 登录页面
     */
    @PostMapping("/check")
    public ResponseEntity<?> checkUser(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();

        User user = userService.findByUsername(username);
        if (user == null) {
            return ResponseEntity.ok(Map.of(
                    "code", 0,
                    "msg", "用户未注册"
            ));
        }

        if (user.getPassword().equals(password)) {
            return ResponseEntity.ok(Map.of(
                    "code", 1,
                    "msg", "登录成功",
                    "data", user
            ));
        } else {
            return ResponseEntity.ok(Map.of(
                    "code", 2,
                    "msg", "密码错误"
            ));
        }
    }

    /**
     * 注册页面
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();

        // 检查用户名是否已存在
        User existingUser = userService.findByUsername(username);
        if (existingUser != null) {
            return ResponseEntity.ok(Map.of(
                    "code", 0,
                    "msg", "用户名已被注册，请重新输入"
            ));
        }
        else{
            // 用户名不存在，新增用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(password);
            userService.saveUser(newUser);

            return ResponseEntity.ok(Map.of(
                    "code", 1,
                    "msg", "注册成功"
            ));
        }

    }

}